import * as Toast from "@/toast"
import axios from 'axios'
import qs from 'qs'

let baseURL = process.env.VUE_APP_BASE_URL
import {getToken, setToken} from "../util/cookie";
import router from '../router'
import store from '../store'
const request = axios.create({
    baseURL: baseURL,
    timeout: 10000,
    headers: {},
    transformRequest: function (data, headers) {
        if (data && data.json) {
            headers['Content-Type'] = 'application/json; charset=UTF-8'
            return JSON.stringify(data)
        }

        return qs.stringify(data, {arrayFormat: 'repeat'})

    }
})

request.interceptors.request.use(function (config) {
    //如果POST需要显示Loading
    if (config.method === 'post' && config.data && config.data.Loading) {
        Toast.showLoading()
    }
    //设置头部
    let token = store.state.user.token
    let tokenName = process.env.VUE_APP_TOKEN_NAME
    if (token) {
        config.headers[tokenName] = token
    }


    // Do something before request is sent
    return config;
}, function (error) {
    // Do something with request error
    Toast.showError("请求错误!")
    return Promise.reject(error);
});


request.interceptors.response.use(function (response) {

    if (response.data.code == process.env.VUE_APP_RES_OK) {
        Toast.hide()
        return response.data
    } else if (response.data.code == process.env.VUE_APP_RES_ERROR) {
        Toast.showError("失败:" + response.data.msg)
        return Promise.reject(response.msg);
    } else if (response.data.code == process.env.VUE_APP_RES_AUTH) {
        Toast.hide()

        //清空token
        store.dispatch('setToken',null)
        // router.push('/login')
        Promise.reject("请先登录!");
    } else {
        Toast.showError("未知业务错误,联系管理员!")
        Promise.reject("未知业务错误,联系管理员!" + response.data.code);
    }
}, function (error) {
    Toast.showError("请重试!"+error)
    // Do something with response error
    return Promise.reject(error);
});

export default request
